package com.mall.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mall.dao.mapper.CommodityMapper;
import com.mall.dao.mapper.SeckillMapper;
import com.mall.model.CommDetailed;
import com.mall.model.Commodity;
import com.mall.model.CommodityExample;
import com.mall.model.CommodityExample.Criteria;
import com.mall.model.Seckill;
import com.mall.model.SeckillExample;
import com.mall.util.MyUtil;
import com.mall.util.RedisUtil;
import com.mall.util.SerializeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class CommodityService {
	@Autowired
	private CommodityMapper commodityMapper;
	@Autowired
	private CommDetailedService commDetailedService;
	@Autowired
	private CommClassService commClassService;
	@Autowired
	private SeckillMapper seckillMapper;

	/**
	 * 上传图片
	 *
	 * @dagewang 2017年8月1日
	 */
	public String uploadImg(MultipartFile m, HttpServletRequest hsr, Integer commid, Integer num) throws Exception {
		String root = null;
		if (!(commid == null || commid.equals("") && num == null || num.equals(""))) {
			root = hsr.getServletContext().getRealPath("/file/detailed/");
		} else {
			root = hsr.getServletContext().getRealPath("/file/img/");
		}
		// 原始文件名称
		String originalFilename = m.getOriginalFilename();
		// 新文件名称
		String newImgName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
		// 创建文件
		File file = new File(root + newImgName);
		// 将文件写入磁盘
		m.transferTo(file);
		if (!(commid == null || commid.equals("") && num == null || num.equals(""))) {
			Commodity c = new Commodity();
			if (num == 1) {
				c.setImg1(newImgName);
			} else if (num == 2) {
				c.setImg2(newImgName);
			} else if (num == 3) {
				c.setImg3(newImgName);
			} else {
				c.setImg4(newImgName);
			}
			c.setId(commid);
			commodityMapper.updateByPrimaryKeySelective(c);
		}
		return newImgName;

	}

	/**
	 * 上传多张商品详细信息图片
	 *
	 * @dagewang 2017年8月1日
	 */
	public String uploadImgD(MultipartFile m, HttpServletRequest hsr) throws Exception {
		// 图片储存路径
		String root = hsr.getServletContext().getRealPath("/file/detailed/");
		// 原始文件名称
		String originalFilename = m.getOriginalFilename();
		// 新文件名称
		String newImgName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
		// 创建文件
		File file = new File(root + newImgName);
		// 将文件写入磁盘
		m.transferTo(file);
		return newImgName;

	}

	/**
	 * 上传多张商品详细信息图片重载,不需要Id
	 *
	 * @dagewang 2017年8月1日
	 */
	public String uploadImgTo(MultipartFile m, HttpServletRequest hsr) throws Exception {
		// 图片储存路径
		String root = hsr.getServletContext().getRealPath("/file/commimg/");
		// 原始文件名称
		String originalFilename = m.getOriginalFilename();
		// 新文件名称
		String newImgName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
		// 创建文件
		File file = new File(root + newImgName);
		// 将文件写入磁盘
		m.transferTo(file);
		return newImgName;

	}

	/**
	 * 添加商品
	 *
	 * @dagewang 2017年8月11日
	 */

	public Commodity saveCommodity(Commodity comm) throws Exception {
		Date date = new Date();
		String commId = UUID.randomUUID().toString();
		comm.setCdate(date);
		comm.setCommodityid(commId);
		comm.setUserid(0);
		comm.setShelves(1);
		comm.setSold(0);
		commodityMapper.insert(comm);
		CommodityExample ex = new CommodityExample();
		ex.createCriteria().andCommodityidEqualTo(commId);
		return commodityMapper.selectByExample(ex).get(0);
	}

	/**
	 * 删除用户上传的零时文件
	 *
	 * @dagewang 2017年8月20日
	 */
	public void deleteImg(String imgName, HttpServletRequest httpServletRequest) throws Exception {
		String root = httpServletRequest.getServletContext().getRealPath("/file/detailed/");
		File file = new File(root + imgName);
		file.delete();
	}

	/**
	 * 获取商品集合
	 * 
	 * @param shelves
	 *
	 * @dagewang 2017年8月20日
	 */
	public List<Commodity> list(Integer page, Integer shelves) throws Exception {
		CommodityExample ex = new CommodityExample();
		ex.setOrderByClause("cdate desc");
		if (shelves != null) {
			ex.createCriteria().andShelvesEqualTo(shelves);
		}
		List<Commodity> list = null;
		RowBounds rowBounds = new RowBounds(page * 5, 5);
		if (shelves != null && shelves == 1) {
			list = commodityMapper.selectByExampleWithRowbounds(ex, rowBounds);
		} else {
			list = commodityMapper.selectByExampleWithRowboundsText(ex, rowBounds);
		}
		return list;
	}

	/**
	 * 获取首页商品集合,按照传入值排序
	 * 
	 * @param page
	 * @param shelves
	 *
	 * @dagewang 2017年8月20日
	 */
	public List<Commodity> indexList(String type, Integer page) throws Exception {
		CommodityExample ex = new CommodityExample();
		if (type != null) {
			ex.setOrderByClause(type);
		} else {
			ex.setOrderByClause("sold desc");
		}
		ex.createCriteria().andShelvesEqualTo(0);
		RowBounds rowBounds = new RowBounds(page * 8, 8);
		List<Commodity> list = commodityMapper.selectByExampleWithRowbounds(ex, rowBounds);
		return list;
	}

	/**
	 * 根据id删除商品
	 *
	 * @dagewang 2017年8月21日
	 */
	public void deleteImg(Integer id) throws Exception {
		commodityMapper.deleteByPrimaryKey(id);
		commClassService.delete(id);

	}

	/**
	 * 搜索商品每页5个
	 *
	 * @dagewang 2017年8月21日
	 */
	public List<Commodity> search(String search, int page) throws Exception {
		RowBounds rowBounds = new RowBounds(page * 5, 5);
		List<Commodity> list = commodityMapper.selectByExampleWithRowboundsLike(search, rowBounds);
		return list;
	}

	/**
	 * 更新商品上下架状态
	 *
	 * @dagewang 2017年8月22日
	 */
	public boolean update(Integer id, Integer shelves) throws Exception {
		Commodity c = commodityMapper.selectByPrimaryKey(id);
		if (c == null) {
			return false;
		}
		c.setUdate(new Date());
		c.setShelves(shelves);
		commodityMapper.updateByPrimaryKey(c);
		return true;
	}

	/**
	 * 更新商品简要信息
	 *
	 * @dagewang 2017年8月22日
	 */
	public boolean update(Commodity comm) {
		Commodity c = commodityMapper.selectByPrimaryKey(comm.getId());
		int i = 0;
		if (c != null) {
			c.setBrand(comm.getBrand());
			c.setCategoryid(comm.getCategoryid());
			c.setTitle(comm.getTitle());
			if (comm.getTitleimg() == null || comm.getTitleimg().equals("")) {
			} else {
				c.setTitleimg(comm.getTitleimg());
			}
			c.setPrice(comm.getPrice());
			c.setParameter(comm.getParameter());
			c.setStock(comm.getStock());
			c.setUdate(new Date());
			i = commodityMapper.updateByPrimaryKey(c);

		}
		if (i != 0) {
			return true;
		}
		return false;
	}

	/**
	 * 获取总页数
	 *
	 * @dagewang 2017年8月23日
	 */
	public Integer pageNum() {
		CommodityExample ex = new CommodityExample();
		int count = commodityMapper.countByExample(ex);
		MyUtil util = new MyUtil();
		Integer page = util.getPage(count, 5);

		return page;
	}

	/**
	 * 获取单个商品的详细信息
	 *
	 * @dagewang 2017年8月29日
	 */
	public List<Object> get(Integer id) throws Exception {
		Commodity selectByPrimaryKey = commodityMapper.selectByPrimaryKey(id);
		CommDetailed cd = commDetailedService.get(id);
		List<Object> list = new ArrayList<Object>();
		list.add(selectByPrimaryKey);
		list.add(cd);
		return list;
	}

	/**
	 * 筛选商品
	 * 
	 * @param categoryid
	 * @dagewang 2017年8月30日
	 */
	public List<Commodity> screen(String meidi, String changhong, String geli, String haier, String ximenzi,
			String qita, Double sprice, Double eprice, String categoryid, Integer page) throws Exception {
		CommodityExample ex = new CommodityExample();
		Criteria c = ex.createCriteria();
		if (!(sprice == null || sprice.equals(""))) {
			ex.setOrderByClause("price asc");
			c.andPriceGreaterThanOrEqualTo(sprice);
		}
		if (!(eprice == null || sprice.equals(""))) {
			c.andPriceLessThanOrEqualTo(eprice);
		}
		List<String> list = new ArrayList<String>();
		if (!(meidi == null || meidi.equals(""))) {
			list.add("美的");
		}
		if (!(haier == null || haier.equals(""))) {
			list.add("海尔");
		}
		if (!(changhong == null || changhong.equals(""))) {
			list.add("长虹");
		}
		if (!(geli == null || geli.equals(""))) {
			list.add("格力");
		}
		if (!(ximenzi == null || ximenzi.equals(""))) {
			list.add("西门子");
		}
		if (!(qita == null || qita.equals(""))) {
			list.add("其他");
		}
		if (list.size() > 0) {
			c.andBrandIn(list);
		}
		if (!(categoryid == null || categoryid.equals(""))) {
			c.andCategoryidEqualTo(categoryid);
		}
		RowBounds rowBounds = new RowBounds(page * 8, 8);
		List<Commodity> selectByExampleWithRowbounds = commodityMapper.selectByExampleWithRowbounds(ex, rowBounds);
		return selectByExampleWithRowbounds;
	}

	public CommodityMapper getCommodityMapper() {
		return commodityMapper;
	}

	public void setCommodityMapper(CommodityMapper commodityMapper) {
		this.commodityMapper = commodityMapper;
	}

	public CommDetailedService getCommDetailedService() {
		return commDetailedService;
	}

	public void setCommDetailedService(CommDetailedService commDetailedService) {
		this.commDetailedService = commDetailedService;
	}

	/**
	 * 根据类型选择商品并排序商品每页8个
	 *
	 * @dagewang 2017年9月2日
	 */
	public List<Commodity> search(String categoryid, Integer page, String type) throws Exception {
		CommodityExample ex = new CommodityExample();
		if (type != null) {
			ex.setOrderByClause(type);
		} else {
			ex.setOrderByClause("sold desc");
		}
		Criteria c = ex.createCriteria();
		c.andShelvesEqualTo(0);
		c.andCategoryidEqualTo(categoryid);
		RowBounds rowBounds = new RowBounds(page * 8, 8);

		List<Commodity> selectByExampleWithRowbounds = commodityMapper.selectByExampleWithRowbounds(ex, rowBounds);
		return selectByExampleWithRowbounds;
	}

	public Commodity getCommById(Integer commid) throws Exception {

		return commodityMapper.selectByPrimaryKey(commid);
	}

	public CommClassService getCommClassService() {
		return commClassService;
	}

	public void setCommClassService(CommClassService commClassService) {
		this.commClassService = commClassService;
	}

	/**
	 * 搜索商品 重载
	 * 
	 * @dagewang 2017年9月21日
	 */
	public List<Commodity> search(String keyword, String sort, Integer page, Double snum, Double ednum)
			throws Exception {
		RowBounds rowBounds = new RowBounds(page * 8, 8);
		MyUtil m = new MyUtil();
		m.setKeys1(keyword);
		m.setKeys2(sort);
		if (snum != null && !snum.equals("")) {
			m.setDs(snum);
		}
		if (ednum != null && !ednum.equals("")) {
			m.setDs2(ednum);
		}
		List<Commodity> list = null;
		try {
			list = commodityMapper.selectByExampleWithRowboundsLikeUser(m, rowBounds);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;

	}
	/**
	 * 提供给redis的首页商品数据
	 *
	 *@dagewang 2017年10月23日
	 */
	public void commListToRedis() throws Exception{
		JedisPool jedis = RedisUtil.getJedis();
		Jedis r = jedis.getResource();
		RowBounds rowBounds=new RowBounds(0,8);
		List<Commodity> selectByRowboundsRedis = commodityMapper.selectByRowboundsRedis(rowBounds);
		SeckillExample ex=new SeckillExample();
		ex.createCriteria().andStateEqualTo(0);
		RowBounds rowbunds2=new RowBounds(0, 2);
		List<Seckill> seckills = seckillMapper.selectByExampleWithRowbounds(ex, rowbunds2);
		if(seckills.size()!=0){
			Seckill[] seckill=new Seckill[seckills.size()];
			Seckill[] array2 =(Seckill[]) seckills.toArray(seckill);
			r.set("seckills".getBytes(), SerializeUtil.serialize(array2));
		}
		Commodity[] c=new Commodity[selectByRowboundsRedis.size()];
		Commodity[] array = selectByRowboundsRedis.toArray(c);
		r.set("commoditys".getBytes(), SerializeUtil.serialize(array));
		
		RedisUtil.close(jedis, r);
	}
}
